<!-- <image-drap-upload v-model="imgUrls"/> -->
<template>
  <div class="uploadWrapper">
    <vuedraggable
      class="vue-draggable"
      :class="{ single: isSingle, maxHidden: isMaxHidden }"
      v-model="imgList"
      tag="ul"
      draggable=".draggable-item"
      @start="onDragStart"
      @end="onDragEnd"
    >
      <!-- 拖拽元素 -->
      <li
        v-for="(item, index) in imgList"
        :key="item + index"
        class="draggable-item"
        :style="{ width: width + 'px', height: height + 'px' }"
      >
        <el-image :src="item.url"></el-image>
        <span class="shadow el-upload-list__item-actions">
          <span @click="onPreviewHandler(index)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span @click="onRemoveHandler(index)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </li>
      <el-upload
        slot="footer"
        ref="uploadRef"
        class="uploadBox"
        :data="{
          // platform:3
        }"
        :style="{ width: width + 'px', height: height + 'px' }"
        :action="uploadUrl"
        :headers="headers"
        accept=".jpg,.jpeg,.png,.gif"
        :show-file-list="false"
        :file-list="imgList"
        :multiple="!isSingle"
        :limit="limit"
        name="files"
        :before-upload="beforeUpload"
        :on-success="onSuccessUpload"
        :on-exceed="onExceed"
      >
        <i class="el-icon-plus uploadIcon"></i>
      </el-upload>
    </vuedraggable>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
  import vuedraggable from 'vuedraggable'
  import lrz from 'lrz' // 前端图片压缩插件
  import {Message} from "element-ui";

  export default {
    name: 'ImageDrapUpload',
    components: { vuedraggable },
    props: {
      // 图片数据(图片url组成的数组) 通过v-model传递
      value: {
        type: Array,
        default() {
          return []
        },
      },
      // 限制上传的图片数量
      limit: {
        type: Number,
        default: 5,
      },
      // 限制上传图片的文件大小(kb)
      size: {
        type: Number,
        default: 10,
      },
      // 是否是单图上传(单图上传就是已传图片和上传按钮重叠)
      isSingle: {
        type: Boolean,
        default: false,
      },
      // 是否使用图片压缩
      useCompress: {
        type: Boolean,
        default: false,
      },
      // 图片显示的宽度(px)
      width: {
        type: Number,
        default: 100,
      },
      // 图片显示的高度(px)
      height: {
        type: Number,
        default: 100,
      },
    },
    data() {
      return {
        headers: {},
        isUploading: false, // 正在上传状态
        isFirstMount: true, // 控制防止重复回显
        dialogVisible: false,
        dialogImageUrl: '',
        uploadUrl: process.env.VUE_APP_UPLOAD_IMG + '/common/uploadFile',
      }
    },
    computed: {
      // 图片数组数据
      imgList: {
        get() {
          return this.value
        },
        set(val) {
          if (val.length < this.imgList.length) {
            // 判断是删除图片时同步el-upload数据
            this.syncElUpload(val)
          }
          // 同步v-model
          this.$emit('input', val)
        },
      },
      // 控制达到最大限制时隐藏上传按钮
      isMaxHidden() {
        return this.imgList.length >= this.limit
      },
    },
    watch: {
      value: {
        handler(val) {
          if (this.isFirstMount && this.value.length > 0) {
            this.syncElUpload()
          }
        },
        deep: true,
      },
      imgList: {
        handler(val) {
          this.$emit('input', val)
        },
        deep: true,
      },
    },
    created() {
      this.headers['Authorization'] = `${this.token}`
      this.headers['tenant'] = this.tenant || localStorage.getItem('tenant')
    },
    mounted() {
      if (this.value.length > 0) {
        this.syncElUpload()
      }
    },
    methods: {
        /**
         * 图片上传
         * @param {file} file el-upload文件对象
         * @param {number} size 限制的文件大小(kb) 默认10M
         */
        validImgUpload(file, size){
            size = +size || 10240;
            const isSizeOut = file.size / 1024 / 1024 > size;
            if(isSizeOut){
              Message({
                type: 'warning',
                message: '图片大小超出限制',
                showClose: true,
              })
            }
            return !isSizeOut;
        },

        /**
         * 创建唯一的字符串
         * @return {string} ojgdvbvaua40
         */
         createUniqueString() {
            const timestamp = +new Date() + "";
            const randomNum = parseInt((1 + Math.random()) * 65536) + "";
            return (+(randomNum + timestamp)).toString(32);
        },


      // 同步el-upload数据
      syncElUpload(val) {
        const imgList = val || this.imgList
        this.$refs.uploadRef.uploadFiles = imgList.map((v, i) => {
          return {
            name: 'pic' + i,
            url: v.url,
            status: 'success',
            uid: this.createUniqueString(),
          }
        })
        this.isFirstMount = false
      },
      beforeUpload(file) {
        this.isFirstMount = false
        let self = this

        if (this.useCompress && file.size/1024/1024 > 2) {
          // 图片压缩
          return new Promise((resolve, reject) => {
            lrz(file, {width: 800})
              .then((rst) => {
                file = rst.file
              })
              .always(() => {
                if (self.validImgUpload(file, self.size)) {
                    self.isUploading = true
                  resolve(file)
                } else {
                  reject(new Error())
                }
              })
          })
        } else {
          if (self.validImgUpload(file, self.size)) {
              self.isUploading = true
            return file
          } else {
            return false
          }
        }
      },
      onSuccessUpload(res, file, fileList) {
        if (res.code == 200) {
          this.imgList.push({
            url: res.data[0].browseUrl,
          })
        } else {
          this.syncElUpload()
            Message({
                message: '上传失败',
                type: 'error',
                showClose: true,
            });
        }
        this.isUploading = false
      },
      onPreviewHandler(index) {
        this.dialogImageUrl = this.imgList[index].url
        this.dialogVisible = true
      },
      onRemoveHandler(index) {
        this.$confirm('确定删除该图片', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.imgList = this.imgList.filter((v, i) => {
              return i !== index
            })
          })
          .catch(() => {})
      },
      onExceed() {
        this.$refs.uploadRef.abort() // 取消剩余接口请求
        this.syncElUpload()
        Message({
          type: 'warning',
          message: '图片数量超出限制',
          showClose: true,
        })
      },
      onDragStart(e) {
        e.target.classList.add('hideShadow')
      },
      onDragEnd(e) {
        e.target.classList.remove('hideShadow')
      },
    },
  }
</script>

<style lang="scss" scoped>
  ::v-deep {
    .el-upload {
      width: 100%;
      height: 100%;
    }
  }
  .uploadIcon {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    font-size: 20px;
    color: #999;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;

    .limitTxt,
    .uploading {
      position: absolute;
      bottom: 10%;
      left: 0;
      width: 100%;
      font-size: 14px;
      text-align: center;
    }
  }
  /* 拖拽 */
  .vue-draggable {
    display: flex;
    flex-wrap: wrap;
    padding: 0;
    margin: 0;
    .draggable-item {
      position: relative;
      margin-right: 5px;
      margin-bottom: 5px;
      overflow: hidden;
      border: 1px solid #ddd;
      border-radius: 6px;
      .el-image {
        width: 100%;
        height: 100%;
      }
      .shadow {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        padding: 2px;
        font-size: 20px;
        line-height: 20px;
        color: #fff;
        cursor: pointer;
        background-color: rgba(0, 0, 0, 0.5);
        opacity: 0;
        transition: opacity 0.3s;
      }
      &:hover {
        .shadow {
          opacity: 1;
        }
      }
    }
    &.hideShadow {
      .shadow {
        display: none;
      }
    }
    &.single {
      position: relative;
      /* overflow: hidden; */
      .draggable-item {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
      }
    }
    &.maxHidden {
      .uploadBox {
        display: none;
      }
    }
  }
  /*  el-image */
  .el-image-viewer__wrapper {
    .el-image-viewer__mask {
      opacity: 0.8;
    }
    .el-icon-circle-close {
      color: #fff;
    }
  }
</style>
